<template>
  <view class="project-list">
    <view class="list-content">
      <view v-if="!projects.length" class="no-content">暂无数据</view>
      <view
          class="project-item"
          v-for="item in projects"
          :key="item.key"
          :class="{ offline: !item.online, 'pending-approve': item.pendingApprove }"
          @click="toProjectDetail(item)"
          @longpress="openMoreAction(item)">
        <image class="item-bg" src="/static/image/project-item-bg.png"></image>
        <view class="project-info">
          <arprogress class="rate-box" :inactiveColor="item.processInactiveColor" :activeColor="item.processActiveColor" :borderWidth="8" :width="120" :percent="item.savingRate">
            <view class="rate-text">
              <view class="progress-rate">
                {{ item.savingRate }}
                <text class="rate-unit">%</text>
              </view>
              <view class="progress-text">节能率</view>
            </view>
          </arprogress>
          <view class="info-box">
            <view class="name-box">
              <view class="project-name">{{ item.name }}</view>
              <view v-if="item.pendingApprove" class="warning-box">
                <text class="iconfont icon-warning-fill"></text>
                <text>申请中</text>
              </view>
              <view v-else-if="item.pendingApproveCount" class="warning-box">
                <text class="iconfont icon-warning-fill"></text>
                <text>待审核: {{ item.pendingApproveCount }}</text>
              </view>
            </view>
            <view class="location-info">{{ item.locationInfo }}</view>
            <view class="admin-info">
              <view class="admin-name">{{ item.userName }}</view>
              <view class="admin-phone">{{ item.phoneShow }}</view>
            </view>
          </view>
        </view>
        <view class="lamp-info">
          <view class="info-item power-total">
            <view class="item-count">{{ item.totalPower }}</view>
            <view class="item-label">
              累计用电
              <text class="small">(Kwh)</text>
            </view>
          </view>
          <view class="info-item power-saving">
            <view class="item-count">{{ item.savingPower }}</view>
            <view class="item-label">
              累计节电
              <text class="small">(Kwh)</text>
            </view>
          </view>
          <view class="info-item error-count">
            <view class="item-count">{{ item.lampErrorCount }}</view>
            <view class="item-label">故障数</view>
          </view>
          <view class="info-item lamp-count">
            <view class="item-count">{{ item.lampTotalCount }}</view>
            <view class="item-label">灯具数</view>
          </view>
        </view>
      </view>
    </view>
    <cover-view v-if="canAdd" class="page-bottom-btn" @click="toAddProject()">新增项目</cover-view>
    <uni-popup ref="popup" type="bottom">
      <cover-view class="delete-btn" @click="deleteProject()">删除项目</cover-view>
    </uni-popup>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
import { formatPhone, fixedDecimal } from '@/utils/index.js'
import color from '@/envs/_/variables.scss'
import arprogress from '@/components/ar-circle-progress/index.vue'
export default {
  components: {
    arprogress
  },
  mixins: [mixin],
  data() {
    return {
	  setupTime: '',
      projects: [],
      targetProject: '',
      targetProjectId: '',
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalPageCount: 0
      }
    }
  },
  onLoad() {
    const self = this
    const app = getApp()
    self.targetProjectId = app.globalData.targetProjectId
    app.globalData.targetProjectId = ''
    if (self.params.gatewayId) {
      self.getProjectByGateway()
    }
  },
  onShow() {
    wx.hideHomeButton()
    this.getProjectList()
  },
  onPullDownRefresh() {
    this.getProjectList()
  },
  methods: {
    setTitle(projectCount) {
      uni.setNavigationBarTitle({
        title: `我的项目${projectCount ? `(${projectCount})` : ''}`
      })
    },
    getProjectList() {
      const self = this
      uni.request({
        url: '/project/list',
        data: {},
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            let target
            result.data.data.forEach(item => {
              // 转换 create_time 格式
              const setupTime = item.create_time.split('T')[0];
              const projectItem = {
                processInactiveColor: color.successLight,
                processActiveColor: color.success,
                key: item.id,
                projectId: item.id,
                name: item.name || '',
                setupTime: setupTime,
                locationInfo: item.address || '',
                userName: item.user_name || '',
                phone: item.phone || '',
                phoneShow: formatPhone(item.phone),
                totalPower: fixedDecimal(item._KWh, 2) || 0,
                savingRate: fixedDecimal(item._rate, 2) || 0,
                lampTotalCount: Math.ceil(item._node_count) || 0,
                lampErrorCount: Math.ceil(item._error_count) || 0,
                lampWarningCount: Math.ceil(item._warning_count) || 0,
                pendingApproveCount: Math.ceil(item.num) || 0,
                online: !!item.online,
                canEdit: item.user_id === self.userInfo.id || self.canEdit,
              }
              if (item.mem_state === 0) {
                projectItem.stateText = '申请中';
                projectItem.pendingApprove = true;
              }
              if (item.mem_state === 2) {
                projectItem.stateText = '申请被拒绝';
                projectItem.pendingApprove = true;
              }
              projectItem.savingPower =  fixedDecimal((projectItem.totalPower * projectItem.savingRate) /  (100 - projectItem.savingRate), 2)
              if (projectItem.lampWarningCount > 99) {
                projectItem.lampWarningCount = '99+'
              }
              if (!projectItem.online) {
                projectItem.processInactiveColor = color.background
                projectItem.processActiveColor = color.backgroundDark
              }
              if (`${self.targetProjectId}` === `${item.id}`) {
                self.targetProjectId = ''
                target = projectItem
              }
              arr.push(projectItem)
            })
            self.projects = arr
            // self.setTitle(self.projects.length)
            if (target) {
              self.toProjectDetail(target)
            }
          }
        },
        complete() {
          uni.stopPullDownRefresh()
        }
      })
    },
    getProjectByGateway() {
      const self = this
      uni.request({
        url: '/project/list',
        data: {
          gateway_id: self.params.gatewayId
        },
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const target = result.data.data[0]
            if (target) {
              self.toProjectDetail(target)
            } else {
              self.toAddProject(self.params.gatewayId)
            }
          }
        },
        complete() {
          uni.stopPullDownRefresh()
        }
      })
    },
    toProjectMap() {
      uni.navigateTo({
        url: '/pages/index/project-map/project-map'
      })
    },
    toAddProject(gatewayId) {
      uni.navigateTo({
        url: `/pages/index/add-project/add-project${gatewayId ? `?gatewayId=${gatewayId}` : ''}`
      })
    },
    toProjectDetail(project) {
      if (project.pendingApprove) return
      uni.navigateTo({
        url: `/pages/project-detail/index/index?id=${project.projectId}`
      })
    },
    openMoreAction(targetProject) {
      if (!targetProject.canEdit) return
      this.targetProject = targetProject
      this.$refs.popup.open()
    },
    deleteProject() {
      const self = this
      if (!self.targetProject) return
      this.$refs.popup.close()
      uni.request({
        url: '/project/del',
        data: {
          id: self.targetProject.projectId
        },
        success(result) {
          if (result.data.success) {
            self.getProjectList()
            uni.showToast({
              icon: 'success',
              title: '删除成功'
            })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.project-list {
  padding-bottom: 120rpx;
  .list-content {
    padding: 20rpx 30rpx;
    .no-content {
      margin-top: 40vh;
      text-align: center;
      color: $text-secondary;
    }
    .project-item {
      margin-top: 20rpx;
      position: relative;
      height: 321rpx;
      padding: 26rpx 30rpx 30rpx 30rpx;
      background-color: $white;
      border-radius: 10rpx;
      &.offline {
        filter: grayscale(1) opacity(0.6);
      }
      &.pending-approve {
        background-color: rgba($warning, 0.08);
      }
      .item-bg {
        position: absolute;
        left: 0;
        top: 0;
        height: 100%;
        width: 100%;
      }
      .project-info {
        position: relative;
        z-index: 2;
        padding-left: 140rpx;
        min-height: 120rpx;
        .rate-box {
          position: absolute;
          left: 0;
          top: 6rpx;
          text-align: center;
          .progress-rate {
            color: $success;
            font-size: $font-size-3;
            .rate-unit {
              font-size: $font-size-0;
            }
          }
          .progress-text {
            font-size: $font-size-0;
          }
        }
        .info-box {
          .name-box {
            position: relative;
            padding-right: 140rpx;
            .project-name {
              font-size: $font-size-4;
              font-weight: bold;
			  // overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }
            .warning-box {
              position: absolute;
              height: 100%;
              top: 0;
              right: 0;
              text-align: right;
              font-size: $font-size-1;
              color: $warning;
              font-weight: normal;
              display: flex;
              align-items: center;
              .iconfont {
                margin-right: 6rpx;
              }
            }
          }
          .location-info {
            margin-top: 4rpx;
            min-height: 20rpx;
            font-size: $font-size-0;
            color: $text-secondary;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .admin-info {
            margin-top: 4rpx;
            font-size: $font-size-3;
            color: $text-base;
            display: flex;
            .admin-name {
              max-width: 320rpx;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }
            .admin-phone {
              margin-left: 10rpx;
            }
          }
        }
      }
      .lamp-info {
        position: relative;
        z-index: 2;
        margin-top: 16rpx;
        padding: 20rpx;
        border-radius: 10rpx;
        background-color: $background-light;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .info-item {
          text-align: center;
          &.power-saving {
            .item-count {
              color: $success;
            }
          }
          .item-count {
            font-size: $font-size-5;
            font-weight: bold;
          }
          .item-label {
            margin-top: 10rpx;
            font-size: $font-size-1;
            color: $text-secondary;
            .small {
              font-size: $font-size-0;
            }
          }
        }
      }
    }
  }
  .to-map {
    position: fixed;
    right: 20rpx;
    bottom: 150rpx;
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    padding: 20rpx;
    background-color: $primary;
    color: $white;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: $font-size-1;
    box-shadow: 0 0 12rpx -2rpx $primary;
  }
}
.delete-btn {
  background-color: $danger;
  color: $white;
  height: 100rpx;
  text-align: center;
  line-height: 100rpx;
  font-size: $font-size-4;
}
</style>
